<?php
namespace App\Http\Controllers\User;

use App\Models\Order\Order;
use App\Models\User\Tihuo;
use Illuminate\Support\Facades\DB;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TihuoController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {

            $Tihuo = $this->filters($request, new Tihuo());

            $paginator = $Tihuo->orderBy($request->get("sidx"), $request->get("sord"))->paginate($request->get("rows"));

            $rows = [];
            foreach ($paginator as $page) {
                $rows[] = $page;
            }

            $data = [
                'rows' => $rows,
                'total'=> $paginator->lastPage(),
                'page' => $paginator->currentPage(),
                'records' => $paginator->count(),
            ];

            return response()->json($data);

        } else {
            return view('user/tihuo');
        }
    }

    public function edit(Request $request) {

        $oper = $request->get('oper');

        if ($oper == "edit") {

            $this->validate($request, [
                'id'     => 'required',
                'status' => 'required'
            ]);

            $tihuo = Tihuo::find($request->get('id'));
            if (!$tihuo) {
                return response()->json(["success" => false]);
            }
            $tihuo->status = $request->get('status');
            $tihuo->desc   = date("Ymd H:i:s") . "\n" . $request->get('desc', "");
            $tihuo->save();
        } elseif ($oper == "del") {
            $this->validate($request, [
                'id' => 'required'
            ]);

            DB::beginTransaction();

            $tihuo = Tihuo::find($request->get('id'));
            if (!$tihuo) {
                return response()->json(["success" => false]);
            }
            if ($tihuo->status != 0) {
                return response()->json(["success" => false , "message" => '已发货后不能删除']);
            }

            $orderId = $tihuo->order_id;
            $order = Order::find($orderId);
            if (!$order) {
                return response()->json(["success" => false]);
            }
            $order->status = 0;
            $order->save();

            $tihuo->delete();

            DB::commit();
        }

        return response()->json(["success" => true]);
    }
}
